package lzzy.edu.cn.demothymeleaf.controller;

import org.springframework.http.HttpHeaders; // 导入 HTTP 头部类
import org.springframework.http.HttpStatus; // 导入 HTTP 状态类
import org.springframework.http.MediaType; // 导入媒体类型类
import org.springframework.http.ResponseEntity; // 导入响应实体类
import org.springframework.stereotype.Controller; // 导入控制器注解
import org.springframework.ui.Model; // 导入模型类，用于传递数据
import org.springframework.web.bind.annotation.GetMapping; // 导入 GET 请求映射注解
import org.springframework.web.bind.annotation.PostMapping; // 导入 POST 请求映射注解
import org.springframework.web.bind.annotation.RequestParam; // 导入请求参数注解
import org.springframework.web.multipart.MultipartFile; // 导入文件上传相关类
import java.io.File; // 导入文件类
import java.io.IOException; // 导入 IO 异常类
import java.net.URLEncoder; // 导入 URL 编码类
import java.nio.file.Files; // 导入文件操作类
import java.util.Objects; // 导入工具类
import java.util.UUID; // 导入 UUID 生成类

@Controller
public class FileController {
    private static final String DIR_PATH = "D:/File/";

    @GetMapping("/upload")
    public String uploadPage() {
        return "upload";
    }

    @PostMapping("/upload")
    public String uploadFile(MultipartFile[] files, Model model) {
        File directory = new File(DIR_PATH);
        if (!directory.exists() && !directory.mkdirs()) {
            model.addAttribute("msg","创建目录失败，请检查服务器配置！");
            return "upload";
        }
        StringBuilder messages = new StringBuilder();
        for(MultipartFile file : files) {
            if (file.isEmpty()){
                messages.append("请选择文件进行上传。<br>");
                continue;
            }

            String fileName = file.getOriginalFilename();
            String uniqueFileName = UUID.randomUUID()+"_"+ Objects.requireNonNull(fileName);
            File destFile = new File(DIR_PATH + uniqueFileName);

            try {
                file.transferTo(destFile);
                messages.append("文件").append(fileName).append("上传成功。<br>");
            } catch (IOException e) {
                messages.append("文件").append(fileName).append("上传失败:").append(e.getMessage()).append("<br>");
            }
        }
        model.addAttribute("msg",messages.toString());
        return "upload";
    }
    @GetMapping("/download")
    public String download(Model model) {
        File dir = new File(DIR_PATH);
        if (dir.exists() && dir.list().length > 0) {
            String[] files = dir.list();
            model.addAttribute("files", files);
        }else {
            model.addAttribute("msg","无下载文件");
        }
        return "download";
    }

    @GetMapping("/downloadfile")
    public ResponseEntity<byte[]> downloadFile(@RequestParam("filename") String fileName) {
        File file = new File(DIR_PATH + fileName);
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentDispositionFormData("attachment", URLEncoder.encode(fileName,"UTF-8"));
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(Files.readAllBytes(file.toPath()));
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED)
                    .body(e.getMessage().getBytes());
        }
    }

    @GetMapping("/login")
    public String tologinPage() {
        return "login/login";
    }

    @GetMapping("/backoffice")
    public String backoffice() {
        return "backOfficeManagement";
    }
//    @PostMapping("/backoffice")

}
